package com.mazaiting.course.controller;

import com.mazaiting.course.domain.Response;
import com.mazaiting.course.exception.CustomException;
import com.mazaiting.course.exception.ExceptionEnum;
import com.mazaiting.course.service.LoginService;
import com.mazaiting.course.utils.RegexMatchesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/***
 * 登录控制器
 * @author mazaiting
 * @datetime 2022/3/7
 */
@RequestMapping("/login")
@RestController
public class LoginController {

    /**
     * 日志框架
     */
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private LoginService service;

    /**
     * Get 请求登录
     */
    @GetMapping("/get")
    public Response loginGet(String username, String password) {
//        logger.info("username: " + username);
//        logger.info("password: " + password);

        // 判断用户名是否为空
        if (StringUtils.isEmpty(username)) {
            throw new CustomException(ExceptionEnum.LOGIN_NULL);
        }
        // 判断密码是否为空
        if (StringUtils.isEmpty(password)) {
            throw new CustomException(ExceptionEnum.PASSWORD_NULL);
        }
        RegexMatchesUtils.isMatches(username);
        // 登录
        return service.login(username, password);
    }

    /**
     * POST 请求登录
     */
    @PostMapping("/post")
    public Response loginPost(@RequestParam Map<String, String> map) {
        // 获得用户名
        String username = map.get("username");



        // 判断用户名是否为空
        if (StringUtils.isEmpty(username)) {
            throw new CustomException(ExceptionEnum.LOGIN_NULL);
        }
        // 获取密码
        String password = map.get("password");

        // 判断密码是否为空
        if (StringUtils.isEmpty(password)) {
            throw new CustomException(ExceptionEnum.PASSWORD_NULL);
        }
        RegexMatchesUtils.isMatches(username);
        // 登录
        return service.login(username, password);
    }

    /**
     * 注册
     * @param request
     * @return
     */
    @PostMapping("/register")
    public Response register(HttpServletRequest request) {

        String username =request.getParameter("username");
        String password = request.getParameter("password");
        RegexMatchesUtils.isMatches(username);
        if (StringUtils.isEmpty(username)) {
            throw new CustomException(ExceptionEnum.LOGIN_NULL);
        }
        if (StringUtils.isEmpty(password)) {
            throw new CustomException(ExceptionEnum.PASSWORD_NULL);
        }
        RegexMatchesUtils.isMatches(username);
        service.register(username, password);
        return new Response(ExceptionEnum.REGISTER_SUCCESS);
    }


}
